import java.sql.*;

public class getResultSetMetaData {
    public static void main(String[] args) {
        String url = "jdbc:opengauss://192.168.163.134:26000/postgres";
        String user = "mogdb";
        String password = "Enmo@123";

        try (Connection conn = DriverManager.getConnection(url, user, password)) {
            Statement stmt = conn.createStatement();

            // 创建表
            String sql = "CREATE TABLE IF NOT EXISTS test_table (" +
                         "id SERIAL PRIMARY KEY, " +
                         "name TEXT NOT NULL, " +
                         "value NUMERIC(9,2) NOT NULL, " +
                         "date TIMESTAMP NOT NULL)";
            stmt.execute(sql);

            // 插入数据
            sql = "INSERT INTO test_table (name, value, date) VALUES (?, ?, ?)";
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, "Test");
            pstmt.setDouble(2, 123.45);
            pstmt.setTimestamp(3, new Timestamp(System.currentTimeMillis()));
            pstmt.executeUpdate();

            // 查询数据
           // ResultSet rs = stmt.executeQuery("SELECT * FROM test_table");
            ResultSet rs = stmt.executeQuery("SELECT * FROM test_table");
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnsNumber = rsmd.getColumnCount();

            // 打印字段名和类型
            for (int i = 1; i <= columnsNumber; i++) {
                System.out.println("Column Name: " + rsmd.getColumnName(i));
                System.out.println("Column Type: " + rsmd.getColumnTypeName(i));
                System.out.println("Precision: " + rsmd.getPrecision(i));
                System.out.println("Scale: " + rsmd.getScale(i));
                System.out.println("-----------------------------");
            }

            // 打印数据
            while (rs.next()) {
                for (int i = 1; i <= columnsNumber; i++) {
                    System.out.print(rs.getString(i) + " ");
                }
                System.out.println();
            }
            stmt.execute("drop table test_table;");
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}